import { DatePicker, message } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { CloneProps } from '@/components/ModalPro';
import { FormItem } from '@/components/FormPro/types';
import React, { useRef, useEffect, useCallback } from 'react';
import { ModalPro, FormPro, SelectFetch } from '@/components';
import getPackagesListService from '@/service/packages/list';
import { positive, phone } from '@/utils/reg';
import addService from '@/service/order/add';

type ProxyProps = {
  onSuccess(): void;
  children: React.ReactElement;
}

type IProps = Omit<ProxyProps, 'children'> & CloneProps;

const formList: FormItem[] = [
  {
    name: 'packagesID',
    label: '套餐',
    render: () => (
      <SelectFetch
        placeholder="选择套餐"
        service={getPackagesListService}
      />
    ),
    rules: [{
      required: true,
      message: '请选择套餐',
    }],
  },
  {
    type: 'input',
    name: 'payPrice',
    label: '支付金额',
    rules: [{
      required: true,
      message: '请输入支付金额',
    }, {
      pattern: positive,
      message: '支付金额只能为正数',
    }],
  },
  {
    type: 'input',
    name: 'mobile',
    label: '用户手机号',
    rules: [{
      required: true,
      message: '请输入手机号',
    },{
      pattern: phone,
      message: '手机号格式不正确'
    }],
  },
  {
    name: 'expiryTime',
    label: '套餐过期时间',
    render: () => (
      <DatePicker style={{width: '100%'}}/>
    )
  },
];

const EditPage: React.FC<IProps> = props => {
  const {
    listenOk,
    submitStop,
    onSuccess,
    closeModal,
    submitLoading
  } = props;

  const formRef = useRef<FormInstance>();

  const onSubmit = useCallback(async () => {
    const fields = await formRef.current?.validateFields();
    const params = {...fields };
    params.packagesID = ~~params.packagesID;
    params.payPrice = ~~params.payPrice;
    /* 时间转为秒 */
    if (params.expiryTime) {
      params.expiryTime = Math.floor((new Date(params.expiryTime).getTime())/1000)
    }
    submitLoading?.();
    try {
      await addService(params);
      onSuccess?.();
      closeModal?.();
      message.success('保存成功');
    }
    catch (e) {
      message.error('保存失败');
    }
    submitStop?.();
  },[])

  useEffect(() => {
    listenOk?.(onSubmit);
  }, []);

  return (
    <FormPro
      formList={formList}
      ref={(e: FormInstance) => (
        formRef.current = e
      )}
    />
  );
};

export default (props: ProxyProps) => {
  const { children } = props;
  return (
    <ModalPro
      width="500px"
      title="新建充值记录"
      children={children}
      triggerContent={<EditPage {...props} />}
    />
  );
}
